<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Bar Statistics</title>
    <!-- Bootstrap Styles-->
    <link href="assets/css/bootstrap.css" rel="stylesheet" />
    <!-- FontAwesome Styles-->
    <link href="assets/css/font-awesome.css" rel="stylesheet" />
    <!-- Morris Chart Styles-->
    <link href="assets/js/morris/morris-0.4.3.min.css" rel="stylesheet" />
    <!-- Custom Styles-->
    <link href="assets/css/custom-styles.css" rel="stylesheet" />
    <!-- Google Fonts-->
    <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' />

  </head>
  <body>
    <!-- <svg width="800" height="800" id="mainsvg" class="svgs" style="background-color: #ffffff;"></svg> -->
    <script src="./d3.min.js"></script>
    <div id="wrapper">
      <nav class="navbar navbar-default top-navbar" role="navigation">
          <div class="navbar-header">
              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".sidebar-collapse">
                  <span class="sr-only">Toggle navigation</span>
                  <span class="icon-bar"></span>
                  <span class="icon-bar"></span>
                  <span class="icon-bar"></span>
              </button>
              <a class="navbar-brand" href="index.html">高管宝典</a>
          </div>  
      </nav>
      <!--/. NAV TOP  -->
      <nav class="navbar-default navbar-side" role="navigation">
          <div class="sidebar-collapse">
              <ul class="nav" id="main-menu">
                  <li>
                      <a href="index.html"><i class="fa fa-dashboard"></i>概览</a>
                  </li>
                  <li>
                      <a href="race.html?feature=institute"><i class="fa fa-desktop"></i> 时间追逐柱状图</a>
                  </li>
                  <li>
                      <a class="active-menu" href="statistics.html?feature=age,salary"><i class="fa fa-bar-chart-o"></i> 多因素统计</a>
                  </li>
                  <li>
                        <a href="personal.html?name=张锡康"><i class="fa fa-search"></i> 个人搜索</a>
                    </li>
                    
                    <li>
                      <a href="map.html"><i class="fa fa-arrows"></i> 关系映射图 </a>
                  </li>
              </ul>

          </div>

      </nav>
      <!-- /. NAV SIDE  -->
      <div id="page-wrapper">
          <div id="page-inner">

            <div class="row">
              <div class="col-md-12">
                  <h1 class="page-header">
                      多因素统计 <small>堆叠柱状图（可选择绝对值、百分比两种模式）</small>
                  </h1>
              </div>
          </div>
          横轴：

          <input type="radio" class="btn-check" name="options-outlined" id="bt1" autocomplete="off">
          <label class="btn btn-outline-success" for="bt1">学历</label>
          
          <input type="radio" class="btn-check" name="options-outlined" id="bt2" autocomplete="off">
          <label class="btn btn-outline-danger" for="bt2">薪资</label>

          <input type="radio" class="btn-check" name="options-outlined" id="bt3" autocomplete="off">
          <label class="btn btn-outline-success" for="bt3">年龄</label>

          <input type="radio" class="btn-check" name="options-outlined" id="bt4" autocomplete="off">
          <label class="btn btn-outline-success" for="bt4">专业</label>

          <input type="radio" class="btn-check" name="options-outlined" id="bt9" autocomplete="off">
          <label class="btn btn-outline-success" for="bt9">任职学校</label>
          
          <br>

          堆叠：
          <input type="radio" class="btn-check" name="options-outlined2" id="bt5" autocomplete="off">
          <label class="btn btn-outline-success" for="bt5">学历</label>
          
          <input type="radio" class="btn-check" name="options-outlined2" id="bt6" autocomplete="off">
          <label class="btn btn-outline-danger" for="bt6">薪资</label>

          <input type="radio" class="btn-check" name="options-outlined2" id="bt7" autocomplete="off">
          <label class="btn btn-outline-success" for="bt7">年龄</label>

          <input type="radio" class="btn-check" name="options-outlined2" id="bt8" autocomplete="off">
          <label class="btn btn-outline-success" for="bt8">专业</label>

          <input type="radio" class="btn-check" name="options-outlined2" id="bt10" autocomplete="off">
          <label class="btn btn-outline-success" for="bt10">任职学校</label>
          
          <br>
          <button id="button3" onclick="jump()" class="btn btn-primary">OK</button>
          


    <svg width="1000" height="700" id="mainsvg" class="svgs"></svg>
    <button id="button1" class="btn btn-primary">Basic Stacked</button>
    <button id="button2" class="btn btn-primary">Percent Stacked</button>
    <script>
      dict = {"bt1":"degree","bt2":"salary","bt3":"age","bt4":"department", "bt9": "institute",
              "bt5":"degree","bt6":"salary","bt7":"age","bt8":"department", "bt10": "institute"}
      function jump()
      {
        var radios = document.getElementsByName("options-outlined");

        //make a dict bt1->degree bt2->salary bt3->age bt4->schoolq
        let selected1
        let selected2
        for(let i = 0; i < radios.length; i++) {
          // 如果该单选框被选中
          if(radios[i].checked) {
            // 打印出选中的单选框的id
            selected1 = dict[radios[i].id]
          }
        }
        radios = document.getElementsByName("options-outlined2");

        for(let i = 0; i < radios.length; i++) {
          // 如果该单选框被选中
          if(radios[i].checked) {
            // 打印出选中的单选框的id
            selected2 = dict[radios[i].id]
          }
        }
        //window.open(`statistics.html?feature=${selected1},${selected2}`);
        window.location.href = `statistics.html?feature=${selected1},${selected2}`
      }
      function check(f1,f2)
      {
        var radios = document.getElementsByName("options-outlined");
        let selected1
        let selected2
        for(let i = 0; i < radios.length; i++) {
          // 如果该单选框被选中
          if(dict[radios[i].id] == f1) {
            // 打印出选中的单选框的id
            radios[i].checked = true
          }
        }
        radios = document.getElementsByName("options-outlined2");

        for(let i = 0; i < radios.length; i++) {
          // 如果该单选框被选中
          if(dict[radios[i].id] == f2) {
            // 打印出选中的单选框的id
            radios[i].checked = true
          }
        }
      }
    
        let stackedData1
        let stackedData2
        let data2
        let subgroups
        let mainGroup
        //Read the data
        feature = window.location.search.split("=")[1];
        f1 = feature.split(",")[0]
        f2 = feature.split(",")[1]
        check(f1,f2)
        xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://127.0.0.1:5000/login', true);
        xhr.setRequestHeader('Content-Type', 'application/json');  // 设置POST传参的请求头(JSON)
        xhr.onreadystatechange = function () {
          if (xhr.readyState !== 4) return;  // readyState == 4 -> 已接收到全部响应数据
          if (xhr.status < 200 || xhr.status >= 300) return;  // 200 <= status <= 299 -> 请求成功
          data = JSON.parse(xhr.responseText)
          console.log(data)
          // Labels of row and columns -> unique identifier of the column called 'group' and 'variable'
    //draw begin
      const svg = d3.select('svg');
      width = svg.attr('width');
      height = svg.attr('height');
    margin = ({top: 16, right: 6, bottom: 50, left: 60});
      const innerWidth = width - margin.left - margin.right;
      const innerHeight = height - margin.top - margin.bottom;
      width = innerWidth
      height = innerHeight
      mainGroup = svg.append('g')
      .attr('transform', `translate(${margin.left}, ${margin.top})`)
    // set the dimensions and margins of the graph
    // Parse the Data
    //     key1 = "age"
    //     key2 = "salary"
    //     value = "value"
      // List of subgroups = header of the csv files = soil condition here

    // console.log(data[0])
        subgroups = data.subname
        console.log(subgroups)

      // List of groups = species here = value of the first column called group -> I show them on the X axis
      const groups = data.group
      data = data["data"]
        console.log(groups)
      // Add X axis
      const x = d3.scaleBand()
          .domain(groups)
          .range([0, width])
          .padding([0.2])
      mainGroup.append("g")
        .attr("transform", `translate(0, ${height})`)
        .call(d3.axisBottom(x).tickSizeOuter(0))
        .selectAll("text")
        .style("font-size", "20px");

      // Add Y axis

      // color palette = one color per subgroup
      const color = d3.scaleOrdinal()
        .domain(subgroups)
        .range(d3.schemeTableau10);

      //stack the data? --> stack per subgroup
      data2 = JSON.parse(JSON.stringify(data));
      stackedData1 = d3.stack()
        .keys(subgroups)
        (data)
      const maxStackHeight = d3.max(stackedData1, d => d3.max(d, layer => layer[1]));
      data2.forEach(function(d){
        // Compute the total
        tot = 0
        for (i in subgroups){ name=subgroups[i] ; tot += +d[name] }
        // Now normalize
        for (i in subgroups){ name=subgroups[i] ; d[name] = d[name] / tot * 100}
      })
      stackedData2 = d3.stack()
        .keys(subgroups)
        (data2)
      const y1 = d3.scaleLinear()
        .domain([0, maxStackHeight])
        .range([ height, 0 ]);
      const y2 = d3.scaleLinear()
          .domain([0, 100])
          .range([height, 0])


      // ----------------
      // Highlight a specific subgroup when hovered
      // ----------------

      // Show the bars

          legend_length = 20
          legend_interval = 30

          var legend = mainGroup.selectAll(".legend")
          .data(Array.from(subgroups)).join('g')
          .attr("class", "legend")
          .attr("transform", (d, i) => `translate(${(40)},${(40)})`)
          .attr("class", d =>"myLegend x" + d.replace('-', '') )
        d3.selectAll(".myLegend").style("opacity", 0)

          legend.append("rect")
            .attr("x", 0)
            .attr("y", -3)
            .attr("width", legend_length)
            .attr("height", legend_length)
            .style("fill", d => color(d));

          // draw legend text
          legend.append("text")
            .attr("x", legend_length + 15)
            .attr("y", 5)
            .attr("dy", ".45em")
            .attr("text-anchor", "start")
            .attr("font-size", '1.5em')
            .text(d => d[0].toUpperCase()+d.slice(1));
      yAxis = mainGroup.append("g")

        yAxis.call(d3.axisLeft(y1))
        .selectAll("text")
        .style("font-size", "16px")
        tmp = mainGroup.append("g")
            tmp.selectAll("g")
            // Enter in the stack data = loop key per key = group per group
            .data(stackedData1)
            .join("g")
              .attr("fill-opacity", 0.8)
              .attr("fill", d => color(d.key))
              .attr("class", d => "myRect x" + d.key.replace('-', '') ) // Add a class to each subgroup: their name
              .selectAll("rect")
              // enter a second time = loop subgroup per subgroup to add all rectangles
            .data(d => d)
            .join("rect")
                .attr("x", d => x(d.data.name))
                .attr("y", d => y1(d[1]))
                .attr("height", d => y1(d[0]) - y1(d[1]))
                .attr("width",x.bandwidth())
                .attr("stroke", "grey")
                .on("mouseover", function (event,d) { // What happens when user hover a bar

                  // what subgroup are we hovering?
                  const subGroupName = d3.select(this.parentNode).datum().key.replace('-', '')

                  // Reduce opacity of all rect to 0.2
                   d3.selectAll(".myRect").style("opacity", 0.2)

                  // Highlight all rects of this subgroup with opacity 1. It is possible to select them since they have a specific class = their name.
                   d3.selectAll(".x"+subGroupName).style("opacity",1)
                })
                .on("mouseleave", function (event,d) { // When user do not hover anymore

                  // Back to normal opacity: 1
                  const subGroupName = d3.select(this.parentNode).datum().key.replace('-', '')
                  d3.selectAll(".x"+subGroupName).style("opacity",0)
                  d3.selectAll(".myRect")
                  .style("opacity",1)
              })
        function changetype(name){
            var newdata
            if(name==='data1')
            {
                stackedData = stackedData1
                y = y1
            }
            else
            {
                stackedData = stackedData2
                y = y2
            }
            yAxis.call(d3.axisLeft(y))
                .selectAll("text")
                .style("font-size", "16px")
             tmp.selectAll("g")
            // Enter in the stack data = loop key per key = group per group
            .data(stackedData)
            .join("g")
              .attr("fill-opacity", 0.8)
              .attr("fill", d => color(d.key))
              .attr("class", d => "myRect x" + d.key.replace('-', '') ) // Add a class to each subgroup: their name
              .selectAll("rect")
              // enter a second time = loop subgroup per subgroup to add all rectangles
            .data(d => d)
            .join("rect")
                .attr("x", d => x(d.data.name))
                .attr("width",x.bandwidth())
                .attr("stroke", "grey")
                .on("mouseover", function (event,d) { // What happens when user hover a bar

                  // what subgroup are we hovering?
                  const subGroupName = d3.select(this.parentNode).datum().key.replace('-', '')

                  // Reduce opacity of all rect to 0.2
                   d3.selectAll(".myRect").style("opacity", 0.2)

                  // Highlight all rects of this subgroup with opacity 1. It is possible to select them since they have a specific class = their name.
                   d3.selectAll(".x"+subGroupName).style("opacity",1)
                })
                .on("mouseleave", function (event,d) { // When user do not hover anymore

                  // Back to normal opacity: 1
                  const subGroupName = d3.select(this.parentNode).datum().key.replace('-', '')
                  d3.selectAll(".x"+subGroupName).style("opacity",0)
                  d3.selectAll(".myRect")
                  .style("opacity",1)
              })
                 .transition(2000)
                .attr("y", d => y(d[1]))
                .attr("height", d => y(d[0]) - y(d[1]))
            // mainGroup.append("g")
            // .selectAll("g")
            // // Enter in the stack data = loop key per key = group per group
            // .data(stackedData)
            // .join("g")
            //   .attr("fill-opacity", 0.8)
            //   .attr("fill", d => color(d.key))
            //   .attr("class", d => "myRect x" + d.key.replace('-', '') ) // Add a class to each subgroup: their name
            //   .selectAll("rect")
            //   // enter a second time = loop subgroup per subgroup to add all rectangles
            //   .data(d => d)
            //   .join("rect")
            //     .attr("x", d => x(d.data.name))
            //     .attr("y", d => y(d[1]))
            //     .attr("height", d => y(d[0]) - y(d[1]))
            //     .attr("width",x.bandwidth())
            //     .attr("stroke", "grey")
            //     .on("mouseover", function (event,d) { // What happens when user hover a bar
            //
            //       // what subgroup are we hovering?
            //       const subGroupName = d3.select(this.parentNode).datum().key.replace('-', '')
            //
            //       // Reduce opacity of all rect to 0.2
            //        d3.selectAll(".myRect").style("opacity", 0.2)
            //
            //       // Highlight all rects of this subgroup with opacity 1. It is possible to select them since they have a specific class = their name.
            //        d3.selectAll(".x"+subGroupName).style("opacity",1)
            //     })
            //     .on("mouseleave", function (event,d) { // When user do not hover anymore
            //
            //       // Back to normal opacity: 1
            //       const subGroupName = d3.select(this.parentNode).datum().key.replace('-', '')
            //       d3.selectAll(".x"+subGroupName).style("opacity",0)
            //       d3.selectAll(".myRect")
            //       .style("opacity",1)
            //   })
        }
            d3.select("#button1").on("click", function() {
                changetype('data1')
            });
            d3.select("#button2").on("click", function() {
                changetype('data2')
            });
          };
       xhr.send(JSON.stringify({type:"statistics", feature: feature, password: 123456}));  // 发送请求, 这里设置POST请求的附加参数
    </script>

  </div>
  <!-- /. PAGE INNER  -->
</div>
<!-- /. PAGE WRAPPER  -->
</div>
<!-- /. WRAPPER  -->
<!-- JS Scripts-->
<!-- jQuery Js -->
<script src="assets/js/jquery-1.10.2.js"></script>
<!-- Bootstrap Js -->
<script src="assets/js/bootstrap.min.js"></script>

<!-- Metis Menu Js -->
<script src="assets/js/jquery.metisMenu.js"></script>
<!-- Morris Chart Js -->
<script src="assets/js/morris/raphael-2.1.0.min.js"></script>
<script src="assets/js/morris/morris.js"></script>


<script src="assets/js/easypiechart.js"></script>
<script src="assets/js/easypiechart-data.js"></script>


<!-- Custom Js -->
<script src="assets/js/custom-scripts.js"></script>
  </body>
</html>